#!/usr/bin/env bash

# $1 - directory with git
if [ -z "$1" ]; then
	exit 1
fi

set -efu
trap popd exit

LOG="${LOG:-$HOME/merge-slava86.log}"

_merge(){
	# relying on set -e to avoid if-else
	MERGE_MSG="no-branch-rosa2019.1"
	git checkout rosa2019.1
	MERGE_MSG="not-mergeable"
	git merge --no-edit rosa2019.05
	MERGE_MSG="merged-but-no-pushed"
	git push origin rosa2019.1
	MERGE_MSG="OK"
}

pushd "$1"

if ! git checkout rosa2019.05 ; then
	echo "FAIL;$1;no-branch-rosa2019.05" | tee -a "$LOG"
	exit 1
fi

if git show HEAD | grep ^Author: | grep -qE 'Святослав|slava86|xer8686@mail.ru|s.matveev@rosalinux.ru'
	then
		if git diff origin/rosa2019.05..origin/rosa2019.1 | grep -q '^\-Version' ; then
			echo "SKIPPED;$1;newer-version" | tee -a "$LOG"
			exit 0
		fi
		if _merge
			then echo "MERGED;$1;$MERGE_MSG" | tee -a "$LOG"
			else echo "FAILED;$1;$MERGE_MSG" | tee -a "$LOG"
		fi
	else
		echo "SKIP;$1;not-slava86" | tee -a "$LOG"
fi
